package com.eightywork.life.fragment;

import cn.jpush.android.api.JPushInterface;

import com.eightywork.life.R;
import com.eightywork.life.activity.AboutActivity;
import com.eightywork.life.activity.BaseActivity;
import com.eightywork.life.activity.EditActivity;
import com.eightywork.life.activity.IdentityActivity;
import com.eightywork.life.activity.LoginMapActivity;
import com.eightywork.life.activity.PasswordModiActivity;
import com.eightywork.life.imageCache.ImageLoader;
import com.eightywork.life.model.Space;
import com.eightywork.life.service.CacheService;
import com.eightywork.life.service.CpService;
import com.eightywork.life.service.DataService;
import com.eightywork.life.service.DoService;
import com.eightywork.life.service.SpaceService;
import com.eightywork.life.util.MyHttpException;
import com.eightywork.life.widget.ActionsContentView;
import com.umeng.analytics.MobclickAgent;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

public class SettingFragment extends BaseFragment implements OnClickListener {
	public static final String TAG = SettingFragment.class.getName();
	private ActionsContentView viewActionsContentView;
	private Activity context;
	private TextView  name, marry, sex, birth, home, qq, realName,
			moblie, address, password, about, verfilyTitle, note, verfyAddress;
	private ImageButton identityBotton, editButton, logoutButton;
	private AsyncTask<?, ?, ?> task;
	private ImageView avatar, verifyType;
	private ImageLoader imageLoader;
	private CheckBox sina, tencent, weixin;
	private View verifystatus, baseinfo, layout1, layout2;

	public SettingFragment(Activity context,
			ActionsContentView viewActionsContentView) {
		this.context = context;
		this.viewActionsContentView = viewActionsContentView;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_setting, container, false);
	}
	
	@Override
	public void onPause() {
	    super.onPause();
	    MobclickAgent.onPause(getActivity());
	}


	@Override
	public void onDestroy() {
		if (task != null) {
			task.cancel(true);
		}
		CacheService.saveSyncWeibo(sina.isChecked(), tencent.isChecked(),
				weixin.isChecked());
		super.onDestroy();
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		initView();
		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public void onResume() {
		initData();
		super.onResume();
		 MobclickAgent.onResume(getActivity());
	}

	private void initView() {
		initHeader("设置", viewActionsContentView);
		identityBotton = (ImageButton) getActivity().findViewById(
				R.id.button_identity);
		editButton = (ImageButton) getActivity().findViewById(R.id.button_edit);
		logoutButton = (ImageButton) getActivity().findViewById(
				R.id.logout_button);
		verifystatus = getActivity().findViewById(R.id.verifystatus);
		baseinfo = getActivity().findViewById(R.id.base_info);
		layout1 = getActivity().findViewById(R.id.layout1);
		layout2 = getActivity().findViewById(R.id.layout2);
		name = (TextView) getActivity().findViewById(R.id.name);
		marry = (TextView) getActivity().findViewById(R.id.marry);
		sex = (TextView) getActivity().findViewById(R.id.sex);
		birth = (TextView) getActivity().findViewById(R.id.birthday);
		home = (TextView) getActivity().findViewById(R.id.home);
		realName = (TextView) getActivity().findViewById(R.id.real_name);
		moblie = (TextView) getActivity().findViewById(R.id.mobile);
		address = (TextView) getActivity().findViewById(R.id.address);
		avatar = (ImageView) getActivity().findViewById(R.id.avatar);
		verifyType = (ImageView) getActivity().findViewById(R.id.verify_type);
		password = (TextView) getActivity().findViewById(R.id.password);
		about = (TextView) getActivity().findViewById(R.id.about_us);
		sina = (CheckBox) getActivity().findViewById(R.id.check_sina);
		tencent = (CheckBox) getActivity().findViewById(R.id.check_tencent);
		weixin = (CheckBox) getActivity().findViewById(R.id.check_weixin);
		verfilyTitle = (TextView) getActivity().findViewById(R.id.verifytile);
		note = (TextView) getActivity().findViewById(R.id.note);
		verfyAddress = (TextView) getActivity()
				.findViewById(R.id.verfy_address);
		verifystatus.setOnClickListener(this);
		identityBotton.setOnClickListener(this);
		editButton.setOnClickListener(this);
		logoutButton.setOnClickListener(this);
		password.setOnClickListener(this);
		about.setOnClickListener(this);
		sina.setOnCheckedChangeListener(new MyOnCheckedChangeListener(
				"您发布的吐槽将会自动同步到新浪微博!"));
		tencent.setOnCheckedChangeListener(new MyOnCheckedChangeListener(
				"您发布的吐槽将会自动同步到腾讯微博!"));
		weixin.setOnCheckedChangeListener(new MyOnCheckedChangeListener(
				"您发布的吐槽将会自动同步到微信朋友圈!"));
	}

	class MyOnCheckedChangeListener implements OnCheckedChangeListener {
		private String message;

		public MyOnCheckedChangeListener(String message) {
			this.message = message;
		}

		@Override
		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked) {
			if (isChecked) {
				getBaseActivity().showMessage(message);
			}
		}
	}

	private void initData() {
		imageLoader = new ImageLoader(getActivity());
		Space space = CacheService.getSpace();
		name.setText(space.getName());
		moblie.setText(space.getMobile());
		note.setText("简介：" + space.getNote());
		sina.setChecked(CacheService.isSyncSinaWeibo());
		weixin.setChecked(CacheService.isSyncWeixin());
		tencent.setChecked(CacheService.isSyncTencentWeibo());
		imageLoader.DisplayImage(space.getAvatar(), avatar, 0, 0, 0);
	    if (space.getVerifyType() != null) {
			verifyType.setVisibility(View.VISIBLE);
			verifyType.setBackgroundResource(DataService.getVerifyTypeRes(space
					.getVerifyType()));
			if (space.getVerifyType().equals("4")) {
				verfilyTitle.setVisibility(View.GONE);
				verifystatus.setVisibility(View.GONE);
				baseinfo.setVisibility(View.GONE);
				verfyAddress.setVisibility(View.VISIBLE);
				layout1.setVisibility(View.GONE);
				layout2.setVisibility(View.GONE);
				verfyAddress.setText("地址：" + space.getVerify_address());
			} else {
				sex.setText("性别：" + DataService.getSexMap().get(space.getSex()));
				Log.d("space.getMarry()", space.getMarry());
				marry.setText("婚恋："
						+ DataService.getMarryMap().get(space.getMarry()));
				birth.setText("生日：" + space.getBirth());
				home.setText("家乡：" + space.getBirthcity());
				realName.setText("真实姓名：" + space.getRealname());
				address.setText("认证地址：" + space.getXiaoquname());
				verfyAddress.setVisibility(View.GONE);
				layout1.setVisibility(View.VISIBLE);
				layout2.setVisibility(View.VISIBLE);
				if (space.getVerifystatus().equals("0")) {
					verifystatus.setVisibility(View.VISIBLE);
					baseinfo.setVisibility(View.GONE);
				} else if (space.getVerifystatus().equals("1")) {
					verifystatus.setVisibility(View.VISIBLE);
					baseinfo.setVisibility(View.GONE);
					((TextView) verifystatus.findViewById(R.id.textView2))
							.setText("已提交认证信息，请耐心等待审核\n点击修改认证>>");
				} else {
					verifystatus.setVisibility(View.GONE);
					baseinfo.setVisibility(View.VISIBLE);
				}
			}
		}
	}

	@Override
	public void onClick(View v) {
	    if (v == identityBotton) {
			Intent intent = new Intent(context, IdentityActivity.class);
			startActivity(intent);
		} else if (v == editButton) {
			Intent intent = new Intent(context, EditActivity.class);
			startActivity(intent);
		} else if (v == logoutButton) {
			AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
			builder.setMessage("你确定要退出登录？");
			builder.setPositiveButton("取消",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
			builder.setNegativeButton("确认",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							//deletePush();
							task = new LogoutTask().execute();
						}
					});
			builder.show();
		} else if (v == password) {
			Intent intent = new Intent(getActivity(),
					PasswordModiActivity.class);
			startActivity(intent);
		} else if (v == about) {
			Intent intent = new Intent(getActivity(), AboutActivity.class);
			startActivity(intent);
		} else if (v == verifystatus) {
			Intent intent = new Intent(getActivity(), IdentityActivity.class);
			startActivity(intent);
		}
	}
	public void deletePush() {
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				JPushInterface.setAliasAndTags(context, "", null);
				JPushInterface.clearAllNotifications(context);
				try {
					SpaceService.deleteToken(CacheService.getSpace().getUid(), CacheService.getSpace().getUid());
				} catch (MyHttpException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
	}

	class ProfileTask extends AsyncTask<Void, Void, String> {
		@Override
		protected void onPreExecute() {
			getBaseActivity().showProgressDialog("请稍后...");
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(Void... params) {
			try {
				CpService.profile();
			} catch (MyHttpException e) {
				return e.getErrorMessage();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			getBaseActivity().hideProgressDialog();
			if (result == null) {

			} else {
			}
			super.onPostExecute(result);
		}
	}

	class LogoutTask extends AsyncTask<Void, Void, String> {
		@Override
		protected void onPreExecute() {
			getBaseActivity().showProgressDialog("正在注销...");
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(Void... params) {
			try {
				DoService.loginout();
				SpaceService.deleteToken(CacheService.getSpace().getUid(), CacheService.getSpace().getUid());
			} catch (MyHttpException e) {
				return e.getErrorMessage();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			getBaseActivity().hideProgressDialog();
			if (result == null) {
				CacheService.clear();
				JPushInterface.setAliasAndTags(context, "", null);
				JPushInterface.clearAllNotifications(context);
				Intent intent = new Intent(context, LoginMapActivity.class);
				startActivity(intent);
				getActivity().finish();
			} else {
				getBaseActivity().showMessage(result);
			}
			super.onPostExecute(result);
		}
	}
}
